import Vue from 'vue'
import axios from 'axios'
import store from '@/store'
import { VueAxios } from './axios'
import { notification, Modal, message } from 'ant-design-vue'
import { ACCESS_TOKEN, TENANTID } from '@/store/mutation-types'
import router from '@/router/index'
import { readAsText } from '@/utils/download'
import { isOpenPay, cancelActivityErr } from './codes'

const baseURL = process.env.VUE_APP_API_BASE_URL
// 创建 axios 实例
const service = axios.create({
  baseURL: baseURL, // api base_url
  timeout: 6000 // 请求超时时间
})

const err = error => {
  if (error.response) {
    const data = error.response.data
    const token = Vue.ls.get(ACCESS_TOKEN)
    if (error.response.status === 403) {
      notification.error({
        message: '服务器错误,请重试',
        description: data.msg
      })
    }
    if (error.response.status === 401 && !(data.result && data.result.isLogin)) {
      notification.error({
        message: '登录过期,请重新登录'
      })
      if (token) {
        store.dispatch('Logout').then(() => {
          setTimeout(() => {
            window.location.reload()
          }, 1500)
        })
      }
    }
  } else if (error.code === 'ECONNABORTED' || error.message === 'Network Error' || error.message.includes('timeout')) {
    message.error('网络超时,请检查您的网络')
  }
  return Promise.reject(error)
}

const isBlobCode = data => {
  if (data instanceof Blob) {
    readAsText(data).then(result => {
      if (result.code) {
        message.error(result.msg || '数据错误,请重试')
      }
    })
  }
}

// request interceptor
service.interceptors.request.use(config => {
  const token = Vue.ls.get(ACCESS_TOKEN)
  const tenantId = Vue.ls.get(TENANTID)
  // config.headers['p-zone-version'] = 'wq' // p-zone-version
  if (process.env.VUE_APP_HEADERS) {
    config.headers['p-zone-version'] = process.env.VUE_APP_HEADERS
  }
  if (token) {
    config.headers['token'] = token // 让每个请求携带自定义 token 请根据实际情况自行修改
    config.headers['tenantId'] = tenantId // 让每个请求携带自定义 tenantId 请根据实际情况自行修改
  }
  return config
}, err)

// response interceptor
service.interceptors.response.use(response => {
  let { config, data } = response
  if (config.responseType === 'blob') {
    data && isBlobCode(data) // 判断blob类型是否业务报错
    return response
  }
  // 单独处理的码
  const codes = [isOpenPay, cancelActivityErr, cancelActivityErr]
  if (data.code && data.code !== 90001 && !codes.includes(data.code)) {
    if (data.code !== 20001) {
      message.error(config.errMsg || data.msg || '操作错误,请重试')
      return Promise.reject(data)
    } else {
      console.log(data.msg)
      Modal.info({
        title: '提示',
        content: data.msg,
        centered: true,
        onOk() { }
      })
    }
  }
  return data
}, err)

const installer = {
  vm: {},
  install(Vue) {
    Vue.use(VueAxios, service)
  }
}

export { installer as VueAxios, service as axios }
